#include "settingsdialog.h"
#include "ui_settingsdialog.h"
#include "smtp\SmtpMime.h"

#include <QDir>
#include <QSettings>
#include <QMessageBox>

SettingsDialog::SettingsDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::SettingsDialog)
{
    ui->setupUi(this);

    model = new QStringListModel(ui->recipients_listView);

    ui->recipients_listView->setModel(model);

    ui->smtp_server_lineEdit->setEmptyMessage("The address of your server");
    ui->smtp_user_lineEdit->setEmptyMessage("user@server.com");
    ui->smtp_pass_lineEdit->setEmptyMessage("Enter your password");
    ui->smtp_sender_lineEdit->setEmptyMessage("Enter your Email Address");
    ui->smtp_subject_lineEdit->setEmptyMessage("Enter the subject message");

    this->loadSettings();

    connect(ui->recipients_listView, SIGNAL(clicked(QModelIndex)), this, SLOT(recipientActivated(QModelIndex)));
}

SettingsDialog::~SettingsDialog()
{
    delete ui;
}

void SettingsDialog::on_min_spinBox_valueChanged(int arg1)
{
    ui->max_spinBox->setMinimum(arg1+1);
}

void SettingsDialog::on_max_spinBox_valueChanged(int arg1)
{
    ui->min_spinBox->setMaximum(arg1+1);
}

void SettingsDialog::accept()
{
    if(!this->checkMailSettings()) return;
    this->saveSettings();
    QDialog::accept();
}

void SettingsDialog::loadSettings()
{
    ui->a_spinBox->setValue(qApp->property("a_constant").toInt());
    ui->b_spinBox->setValue(qApp->property("b_constant").toInt());
    ui->delta_doubleSpinBox->setValue(qApp->property("delta").toDouble());
    ui->attempts_spinBox->setValue(qApp->property("attempts").toInt());
    ui->alarm_groupBox->setChecked(qApp->property("alarm").toBool());
    ui->max_spinBox->setValue(qApp->property("max_temp").toInt());
    ui->min_spinBox->setValue(qApp->property("min_temp").toInt());
    ui->autorun_checkBox->setChecked(qApp->property("autorun").toBool());
    ui->minimized_checkBox->setChecked(qApp->property("minimized").toBool());
    ui->delay_spinBox->setValue(qApp->property("delay_run").toInt());
    ui->updates_checkBox->setChecked(qApp->property("auto_updates").toBool());
    //smtp
    ui->smtp_user_lineEdit->setText(qApp->property("smtp_user").toString());
    ui->smtp_pass_lineEdit->setText(qApp->property("smtp_pass").toString());
    ui->smtp_server_lineEdit->setText(qApp->property("smtp_server").toString());
    ui->smtp_sender_lineEdit->setText(qApp->property("smtp_sender").toString());
    ui->smtp_subject_lineEdit->setText(qApp->property("smtp_subject").toString());
    ui->type_comboBox->setCurrentIndex(ui->type_comboBox->findText(qApp->property("smtp_type").toString()));
    this->on_type_comboBox_activated(qApp->property("smtp_type").toString());
    model->setStringList(qApp->property("smtp_recipients").toStringList());
    ui->smtp_interval_spinBox->setValue(qApp->property("smtp_interval").toInt());
    ui->smtp_port_spinBox->setValue(qApp->property("smtp_port").toInt());
    //graphics
    ui->graphics_groupBox->setChecked(qApp->property("graphics_show").toBool());
    ui->step_spinBox->setValue(qApp->property("graphics_step").toInt());
    ui->history_spinBox->setValue(qApp->property("graphics_history").toInt());
    //database
    ui->history_groupBox->setChecked(qApp->property("save_history").toBool());

    QSettings startup("HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", QSettings::NativeFormat);
    ui->autostart_checkBox->setChecked(startup.value("serialtemper").toString() == QDir::toNativeSeparators(qApp->applicationFilePath()));
}

void SettingsDialog::saveSettings()
{
    qApp->setProperty("a_constant", ui->a_spinBox->value());
    qApp->setProperty("b_constant", ui->b_spinBox->value());
    qApp->setProperty("delta", ui->delta_doubleSpinBox->value());
    qApp->setProperty("attempts", ui->attempts_spinBox->value());
    qApp->setProperty("alarm", ui->alarm_groupBox->isChecked());
    qApp->setProperty("max_temp", ui->max_spinBox->value());
    qApp->setProperty("min_temp", ui->min_spinBox->value());
    qApp->setProperty("autorun", ui->autorun_checkBox->isChecked());
    qApp->setProperty("minimized", ui->minimized_checkBox->isChecked());
    qApp->setProperty("delay_run", ui->delay_spinBox->value());
    qApp->setProperty("auto_updates", ui->updates_checkBox->isChecked());
    /*SMTP*/
    qApp->setProperty("smtp_type", ui->type_comboBox->currentText());
    qApp->setProperty("smtp_server", ui->smtp_server_lineEdit->text());
    qApp->setProperty("smtp_user", ui->smtp_user_lineEdit->text());
    qApp->setProperty("smtp_pass", ui->smtp_pass_lineEdit->text());
    qApp->setProperty("smtp_sender", ui->smtp_sender_lineEdit->text());
    qApp->setProperty("smtp_subject", ui->smtp_subject_lineEdit->text());
    qApp->setProperty("smtp_recipients", model->stringList());
    qApp->setProperty("smtp_interval", ui->smtp_interval_spinBox->value());
    qApp->setProperty("smtp_port", ui->smtp_port_spinBox->value());
    /*Graphics*/
    qApp->setProperty("graphics_show", ui->graphics_groupBox->isChecked());
    qApp->setProperty("graphics_step", ui->step_spinBox->value());
    qApp->setProperty("graphics_history", ui->history_spinBox->value());
    /*Database*/
    qApp->setProperty("save_history", ui->history_groupBox->isChecked());

    //QDir appdir = qApp->applicationDirPath();
    QDir appdir = QDir::home();
    QSettings settings(appdir.filePath("SerialTemper.ini"), QSettings::IniFormat);
    settings.beginGroup("Program");
    settings.setValue("Autorun", qApp->property("autorun").toBool());
    settings.setValue("DelayRun", qApp->property("delay_run").toInt());
    settings.setValue("AutoUpdates", qApp->property("auto_updates").toBool());
    settings.endGroup();
    settings.beginGroup("Interface");
    settings.setValue("Minimized", qApp->property("minimized").toBool());
    settings.endGroup();
    settings.beginGroup("Settings");
    settings.setValue("AConstant", qApp->property("a_constant").toInt());
    settings.setValue("BConstant", qApp->property("b_constant").toInt());
    settings.setValue("Delta", qApp->property("delta").toDouble());
    settings.setValue("Attempts", qApp->property("attempts").toInt());
    settings.setValue("Alarm", qApp->property("alarm").toDouble());
    settings.setValue("MaxTemp", qApp->property("max_temp").toInt());
    settings.setValue("MinTemp", qApp->property("min_temp").toInt());
    settings.endGroup();
    settings.beginGroup("SMTP");
    settings.setValue("SmtpType", qApp->property("smtp_type").toString());
    settings.setValue("SmtpServer", qApp->property("smtp_server").toString());
    settings.setValue("SmtpUser", qApp->property("smtp_user").toString());
    QByteArray ba;
    ba.append(qApp->property("smtp_pass").toString());
    settings.setValue("SmtpPass",  ba.toBase64());
    settings.setValue("SmtpSender", qApp->property("smtp_sender").toString());
    settings.setValue("SmtpSubject", qApp->property("smtp_subject").toString());
    settings.setValue("SmtpRecipients", qApp->property("smtp_recipients"));
    settings.setValue("SmtpInterval", qApp->property("smtp_interval").toInt());
    settings.setValue("SmtpPort", qApp->property("smtp_port").toInt());
    settings.endGroup();
    settings.beginGroup("Graphics");
    settings.setValue("GraphicsShow", qApp->property("graphics_show").toBool());
    settings.setValue("GraphicsStep", qApp->property("graphics_step").toInt());
    settings.setValue("GraphicsHistory", qApp->property("graphics_history").toInt());
    settings.endGroup();
    settings.beginGroup("Database");
    settings.setValue("SaveHistory", qApp->property("save_history").toBool());
    settings.endGroup();

    QSettings startup("HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", QSettings::NativeFormat);
    if(ui->autostart_checkBox->isChecked()) startup.setValue("serialtemper", QDir::toNativeSeparators(qApp->applicationFilePath()));
    else startup.remove("serialtemper");
}

void SettingsDialog::on_smtp_test_pushButton_clicked()
{
    if(!this->checkMailSettings()) return;
    SmtpClient smtp;
    // Now we create a MimeMessage object. This is the email.

    MimeMessage message;
    MimeText text;
    if(ui->type_comboBox->currentText() == "Gmail"){
        QString host(ui->smtp_server_lineEdit->text());
        //QString host("smtp.gmail.com");
        smtp.setHost(host);
        //smtp.setPort(465);
        smtp.setPort(ui->smtp_port_spinBox->value());
        smtp.setConnectionType(SmtpClient::SslConnection);
        smtp.setUser(ui->smtp_user_lineEdit->text());
        smtp.setPassword(ui->smtp_pass_lineEdit->text());
        message.setSender(new EmailAddress(ui->smtp_user_lineEdit->text(), ui->smtp_sender_lineEdit->text()));
        //message.addRecipient(new EmailAddress("georgiev@toplo-pleven.com", "Venelin Georgiev"));
        QStringList list = model->stringList();
        foreach (const QString &str, list) {
            message.addRecipient(new EmailAddress(str, str));
        }

        message.setSubject(ui->smtp_subject_lineEdit->text());
        text.setText("Hi,\nThis is a simple test email message.\n");
        message.addPart(&text);
        smtp.connectToHost();
        smtp.login();
    }
    else if (ui->type_comboBox->currentText() == "SMTP without login"){
        QString host(ui->smtp_server_lineEdit->text());
        smtp.setHost(host);
        //smtp.setPort(25);
        smtp.setPort(ui->smtp_port_spinBox->value());
        smtp.setConnectionType(SmtpClient::TcpConnection);
        message.setSender(new EmailAddress(ui->smtp_sender_lineEdit->text(), ui->smtp_sender_lineEdit->text()));
        //message.addRecipient(new EmailAddress("georgiev@toplo-pleven.com", "Venelin Georgiev"));
        QStringList list = model->stringList();
        foreach (const QString &str, list) {
            message.addRecipient(new EmailAddress(str, str));
        }
        message.setSubject(ui->smtp_subject_lineEdit->text());
        text.setText("Hi,\nThis is a simple test email message.\n");
        message.addPart(&text);
        smtp.connectToHost();
       // smtp.login();
    }
    else if(ui->type_comboBox->currentText() == "SMTP with login"){
        QString host(ui->smtp_server_lineEdit->text());
        smtp.setHost(host);
        //smtp.setPort(465);
        smtp.setPort(ui->smtp_port_spinBox->value());
        smtp.setConnectionType(smtp.getPort() != 25 ? SmtpClient::SslConnection : SmtpClient::TcpConnection);
        smtp.setAuthMethod(SmtpClient::AuthPlain);
        smtp.setUser(ui->smtp_user_lineEdit->text());
        smtp.setPassword(ui->smtp_pass_lineEdit->text());
        message.setSender(new EmailAddress(ui->smtp_user_lineEdit->text(), ui->smtp_sender_lineEdit->text()));
        QStringList list = model->stringList();
        foreach (const QString &str, list) {
            message.addRecipient(new EmailAddress(str, str));
        }

        message.setSubject(ui->smtp_subject_lineEdit->text());
        text.setText("Hi,\nThis is a simple test email message.\n");
        message.addPart(&text);
        /*debug*/
        ((QSslSocket*)smtp.getSocket())->setPeerVerifyMode(QSslSocket::VerifyNone);

        smtp.connectToHost();
        smtp.login();
    }

    if(ui->type_comboBox->currentText() == "NTLM"){
        QString host(ui->smtp_server_lineEdit->text());
        smtp.setHost(host);
        smtp.setPort(ui->smtp_port_spinBox->value());
        smtp.setAuthMethod(SmtpClient::AuthNtlm);
        //smtp.setConnectionType(SmtpClient::SslConnection);
        smtp.setUser(ui->smtp_user_lineEdit->text());
        smtp.setPassword(ui->smtp_pass_lineEdit->text());
        message.setSender(new EmailAddress(ui->smtp_user_lineEdit->text(), ui->smtp_sender_lineEdit->text()));
        QStringList list = model->stringList();
        foreach (const QString &str, list) {
            message.addRecipient(new EmailAddress(str, str));
        }

        message.setSubject(ui->smtp_subject_lineEdit->text());
        text.setText("Hi,\nThis is a simple test email message.\n");
        message.addPart(&text);
        //((QSslSocket*)smtp.getSocket())->setProtocol(QSsl::TlsV1);
        //((QSslSocket*)smtp.getSocket())->setPeerVerifyMode(QSslSocket::VerifyNone);
        smtp.connectToHost();
        smtp.login();
    }

    if(!smtp.sendMail(message)){
        QMessageBox msgBox;
         msgBox.setText(tr("Error: %1").arg(smtp.getSocket()->errorString()));
         msgBox.exec();
    }
    else{
        QMessageBox msgBox;
         msgBox.setText(tr("SMTP test is OK :)"));
         msgBox.exec();
    }
    smtp.quit();
}

void SettingsDialog::on_add_recipient_toolButton_clicked()
{
    bool ok;
    QString text = QInputDialog::getText(this, tr("Enter e-mail address"), tr("Address:"), QLineEdit::Normal, "", &ok);
    if (ok && !text.isEmpty()){
       QStringList list = model->stringList();
       list << text;
       model->setStringList(list);
    }
}

void SettingsDialog::recipientActivated(const QModelIndex &index)
{
    ui->recipient_remove_toolButton->setEnabled(index.isValid());
}

void SettingsDialog::on_recipient_remove_toolButton_clicked()
{
    QModelIndex index = ui->recipients_listView->selectionModel()->currentIndex();
    if(index.isValid()){
        ui->recipients_listView->model()->removeRow(index.row());
    }
}

void SettingsDialog::on_type_comboBox_activated(const QString &arg1)
{
    if(arg1 == "Gmail"){
        ui->smtp_user_lineEdit->setDisabled(false);
        ui->smtp_pass_lineEdit->setDisabled(false);
        ui->smtp_server_lineEdit->setText("smtp.gmail.com");
        ui->smtp_user_lineEdit->setEmptyMessage("user@gmail.com");
        ui->smtp_sender_lineEdit->setEmptyMessage("Your name");
        ui->smtp_port_spinBox->setValue(465);
    }
    else if(arg1 == "SMTP without login"){
        ui->smtp_user_lineEdit->setDisabled(true);
        ui->smtp_pass_lineEdit->setDisabled(true);
        ui->smtp_user_lineEdit->setEmptyMessage("user@yourserver.com");
        ui->smtp_server_lineEdit->setEmptyMessage("Address of your server");
        ui->smtp_sender_lineEdit->setEmptyMessage("user@yourserver.com");
        ui->smtp_port_spinBox->setValue(25);
    }
    else if(arg1 == "SMTP with login"){
        ui->smtp_user_lineEdit->setDisabled(false);
        ui->smtp_pass_lineEdit->setDisabled(false);
        ui->smtp_user_lineEdit->setEmptyMessage("user@yourserver.com");
        ui->smtp_server_lineEdit->setEmptyMessage("Address/name of your server");
        ui->smtp_sender_lineEdit->setEmptyMessage("user@yourserver.com");
        ui->smtp_port_spinBox->setValue(465);
    }
    else if(arg1 == "NTLM"){
        ui->smtp_user_lineEdit->setDisabled(false);
        ui->smtp_pass_lineEdit->setDisabled(false);
        ui->smtp_user_lineEdit->setEmptyMessage("user@domain");
        ui->smtp_server_lineEdit->setEmptyMessage("Address/name of your server");
        ui->smtp_sender_lineEdit->setEmptyMessage("Your name");
        ui->smtp_port_spinBox->setValue(587);
    }
}

bool SettingsDialog::checkMailSettings()
{
    if(!ui->alarm_groupBox->isChecked()) return true;
    if(ui->smtp_server_lineEdit->text().isEmpty()){
        QMessageBox msgBox;
        msgBox.setIcon(QMessageBox::Warning);
        msgBox.setText("The smtp server adress/name is missing.");
        msgBox.exec();
        ui->smtp_server_lineEdit->setFocus();
        return false;
    }
    if(ui->smtp_port_spinBox->value() == 0){
        QMessageBox msgBox;
        msgBox.setIcon(QMessageBox::Warning);
        msgBox.setText("The smtp port is invalid.");
        msgBox.exec();
        ui->smtp_port_spinBox->setFocus();
        return false;
    }
    if(ui->type_comboBox->currentText() == "Gmail" || ui->type_comboBox->currentText() == "SMTP with login" ){
        if(ui->smtp_user_lineEdit->text().isEmpty()){
            QMessageBox msgBox;
            msgBox.setIcon(QMessageBox::Warning);
            msgBox.setText("The smtp user adress is missing.");
            msgBox.exec();
            ui->smtp_user_lineEdit->setFocus();
            return false;
        }
    }
    if(ui->smtp_sender_lineEdit->text().isEmpty()){
        QMessageBox msgBox;
        msgBox.setIcon(QMessageBox::Warning);
        msgBox.setText("The smtp sender adress/name is missing.");
        msgBox.exec();
        ui->smtp_sender_lineEdit->setFocus();
        return false;
    }
    if(ui->smtp_subject_lineEdit->text().isEmpty()){
        QMessageBox msgBox;
        msgBox.setIcon(QMessageBox::Warning);
        msgBox.setText("The smtp subject msg is missing.");
        msgBox.exec();
        ui->smtp_subject_lineEdit->setFocus();
        return false;
    }
    if(model->stringList().count() < 1){
        QMessageBox msgBox;
        msgBox.setIcon(QMessageBox::Warning);
        msgBox.setText("Message must have at least one recipient.");
        msgBox.exec();
        return false;
    }
    return true;
}
